package cn.rocky.zuosheng;

public class CodeSmallSum {

    public static void smallSum(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        process(arr, 0, arr.length - 1);
    }

    // arr[L..R] 既要排好序,也要求小和
    public static int process(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }
        int mid = L + ((R - L) >> 1);
        return process(arr, 1, mid)
                + process(arr, mid + 1, R)
                + merge(arr, 1, mid, R);
    }

    public static int merge(int[] arr, int L, int Mid, int R) {
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;
        int p2 = Mid + 1;
        int res = 0;
        while (p1 <= Mid && p2 <= R) {
            res += arr[p1] < arr[p2]
                    ? (R - p2 + 1) * arr[p1]
                    : 0;
            // 小数和 不能等于 用下标确认数量
            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= Mid) {
            help[i++] = arr[p1++];
        }
        while (p2 <= Mid) {
            help[i++] = arr[p2++];
        }
        for (i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
        return res;
    }
}
